<template>
  <div class="usage-record-tab">
    <el-table :data="tableData" v-loading="loading" border height="100%">
      <el-table-column prop="requirementId" label="需求编号" width="180" show-overflow-tooltip />

      <el-table-column
        prop="requirementName"
        label="需求名称"
        min-width="200"
        show-overflow-tooltip
      />

      <el-table-column prop="usedVersion" label="使用版本" width="120" show-overflow-tooltip />

      <el-table-column prop="creator" label="创建人" width="150" show-overflow-tooltip />

      <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip />

      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-link type="primary" @click="goToView(row)">前往查看</el-link>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="total"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        @current-change="handlePageChange"
        @size-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { usageRecord } from '@/api/system/materials'

const props = defineProps({
  materialId: {
    type: [String, Number],
    required: true
  }
})

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])

// 获取使用记录数据
const getUsageRecord = async () => {
  loading.value = true
  try {
    const params = {
      id: props.materialId,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    const res = await usageRecord(params)
    tableData.value = res.data.list || []
    total.value = res.data.total || 0
  } catch (error) {
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分页改变
function handlePageChange() {
  getUsageRecord()
}

function goToView(row) {
  ElMessage.info(`前往查看：${row.requirementName}`)
}

onMounted(() => {
  getUsageRecord()
})
</script>

<style lang="scss" scoped>
.usage-record-tab {
  height: 100%;
  display: flex;
  flex-direction: column;

  .pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
